package logic

import (
	"cart/model/cache"
	"cart/model/mysqls"
	"context"
	"fmt"

	"cart/cartrpc/cartrpc"
	"cart/cartrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cartrpc.CartAddRequest) (*cartrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	if in.Num > 20 {
		return nil, fmt.Errorf("商品限购20件")
	}

	var shop mysqls.Shop
	mysqls.DB.Where("id=?", in.ShopId).First(&shop)
	if shop.ID == 0 {
		return nil, fmt.Errorf("该商品不存在")
	}

	key := fmt.Sprintf("KeyXu:%d", in.ShopId)
	Keys := cache.Rdb.LLen(l.ctx, key).Val()
	if Keys < in.Num {
		return nil, fmt.Errorf("虚拟库存不足")
	}

	if cache.IsKeyExes(int(in.UserId), int(in.ShopId)) {
		err := cache.ShopUpdates(int(in.UserId), int(in.ShopId), int(in.Num))
		if err != nil {
			return nil, fmt.Errorf("商品数量修改失败")
		}
	} else {
		CartMap := map[string]interface{}{
			"ShopName": shop.ShopName,
			"Price":    shop.Price,
			"Num":      shop.Num,
			"Image":    shop.Image,
			"Status":   shop.Status,
		}
		err := cache.ShopAdds(int(in.UserId), int(in.ShopId), CartMap)
		if err != nil {
			return nil, fmt.Errorf("商品添加失败")
		}
	}

	return &cartrpc.CartAddResponse{
		Success: true,
		Message: "商品添加成功",
	}, nil
}
